import http.client, urllib.request, urllib.parse, urllib.error, base64
import json
# import pymysql
import time



headers = {
    # Request headers
    'Ocp-Apim-Subscription-Key': '2b2d0872e48c40908b97b71765c951e5',
}




def reviewdata_insert(key_name, recursion):
    try:
        # time.sleep(0.3)
        params = urllib.parse.urlencode({
            'expr': "FN='" + key_name + "'",
            'model': 'latest',
            'count': 1,
            'offset': 0,
            'attributes': '*',
        })
        conn = http.client.HTTPSConnection('api.labs.cognitive.microsoft.com')
        conn.request("GET", "/academic/v1.0/evaluate?%s" % params, "{body}", headers)
        response = conn.getresponse()
        data = response.read()
        if "error" in json.loads(data.decode()):
            print("error")
        if "entities" in json.loads(data.decode()):
            f_item = json.loads(data.decode())["entities"]
            if len(f_item) > 0:
                item = f_item[0]
                f = open('E:/fields.txt', 'a')
                f.write('\n' + json.dumps(item))
                print(item)
                f.close()
                # for item in json.loads(data.decode())["entities"]:
                result = []
                id = item["Id"]
                fn = item["FN"]
                fc = None
                fp = None
                if recursion:
                    if 'FC' in item:
                        fc = json.dumps(item["FC"])
                        # for child in item["FC"]:
                            # reviewdata_insert(child["FN"], True)
                    if 'FP' in item:
                        fp = json.dumps(item["FP"])
                        # for child in item["FP"]:
                            # reviewdata_insert(child["FN"], False)
                # if 'RF' in item:
                #    rf = json.dumps(item["RF"])


                # result.append((id, cc, ecc, dfn, fn, fc, fp, rf))
                # insert_re = "insert into test(Id, CC, ECC, DFN, FN, FC, FP, RF) values (%s, %s, %s, %s, %s, %s, %s, %s)"
                # cursor = db.cursor()
                # cursor.executemany(insert_re, result)
                # db.commit()
        conn.close()

    except Exception as e:
        print("[Errno {0}] {1}".format(e.errno, e.strerror))



if __name__ == "__main__":
    reviewdata_insert("quantum", True)




